import { Question, ch2en_map, ch2number_map } from './type'
import { base_url } from './config'
import { optimizationElementWithImage, removeRedundantWords, StringUtils } from "./OCSFunction.ts";
import { InfoNotFoundError } from "./error.ts";

let questions: Question[] = []
let warnings: string[] = []
const submit_answer = (question: string, answer: string, question_type: string, options?: string[]) => {
    let body: Question = {
        "question": question,
        "answer": answer,
        "type": question_type,
    }
    if (options) {
        body.options = options;
    }
    // console.log("检测到题目: ", body)
    questions.push(body);
}

const common_question_getter = (element: HTMLElement) => {
    const title = element.querySelector("h3.mark_name")?.cloneNode(true) as HTMLElement
    if (title === undefined) {
        throw new InfoNotFoundError("无法获取题目标题");
    }
    title.childNodes[0].remove()
    title.childNodes[0].remove()
    let titleString = optimizationElementWithImage(title).innerText
    return removeRedundantWords(
        StringUtils.of(titleString).nowrap(' ').nospace().toString().trim()
    );
}

const common_options_getter = (element: HTMLElement) => {
    let options: string[] = []
    element.querySelectorAll(".mark_letter li").forEach((element) => {
        optimizationElementWithImage(element as HTMLElement)
        options.push((element as HTMLElement).innerText.replace(/^[A-Z]\. */, "").trim())
    })
    return options
}

const simple_answer_getter = (_index: number, element: HTMLElement, question_type: string) => {
    element.querySelectorAll("div.aiAreaContent").forEach((element, index) => {
        let question = common_question_getter(element as HTMLElement);
        let options = common_options_getter(element as HTMLElement)
        let answer_option = element.querySelector(".mark_answer")?.querySelector(".rightAnswerContent")?.textContent;
        let answer = element.querySelector(".mark_answer")?.querySelector(".element-invisible-hidden.colorGreen")?.textContent;
        // 如果没有答案，通过得分判断自己的答案是否正确
        if (!answer && question_type == "单选题") {
            const score = parseInt(element.querySelector(".mark_score")?.textContent!.trim().match(/\d+/)?.[0] ?? "-1")
            if (score > 0) {
                answer_option = element.querySelector(".mark_answer")?.querySelector(".stuAnswerContent")?.textContent;
                answer = element.querySelector(".mark_answer")?.querySelector(".element-invisible-hidden.colorDeep")?.textContent;
            }
        }
        if (!question || !answer){
            throw new InfoNotFoundError("Question or answer not found in simple for index of "+index);
        }
        // 移除答案开头的冒号和末尾的分号
        if (answer.startsWith(':')) {
            answer = answer.slice(1);
        }
        if (answer.endsWith('; ')) {
            answer = answer.slice(0, -2);
        }
        // 将答案中的分号替换为#
        if (question_type === "multiple") {
            answer = answer.replace(/(;*);+/g, '$1#');
        }
        // 优先从options中获取选项
        if (answer_option) {
            answer = options[letterToNumber(answer_option)];
        }
        submit_answer(question, answer, question_type, options);
    })
}
const judgement_answer_getter = (_index: number, element: HTMLElement, question_type: string) => {
    element.querySelectorAll("div.aiAreaContent").forEach((element, index) => {
        let question = common_question_getter(element as HTMLElement);
        let answer = element.querySelector(".mark_answer")?.querySelector(".colorGreen")?.childNodes[2].textContent?.trim()
        if (!question || !answer){
            throw new InfoNotFoundError("Question or answer not found in judgement for index of "+index);
        } else {
            submit_answer(question, answer, question_type);
        }
    })
}

const completion_answer_getter = (_index: number, element: HTMLElement, question_type: string) => {
    element.querySelectorAll("div.aiAreaContent").forEach((element, index) => {
        let question = common_question_getter(element as HTMLElement);
        let answer_list: string[] = []
        element.querySelector(".mark_answer")?.querySelectorAll(".colorGreen dd")
            .forEach((element)=>{
                let temp = element.textContent?.trim()
                    .replace(/^\s*\(\d+\)\s*/g, "")         // 去除序号和冗余空格
                    .split(";")[0]                   // 获取第一个分号前的答案
                    .replace(/;$/,"") ?? ""                 // 去除末尾的分号
                answer_list.push(temp)
            })
        if (!question || !answer_list){
            throw new InfoNotFoundError("Question or answer not found in completion for index of "+index);
        } else {
            const answer = answer_list.join("###");
            submit_answer(question, answer, question_type);
        }
    })
}

const question_type_getter = (_index: number, element: HTMLElement): [number|null, string|null] => {
    let typeTitElement = element.querySelector(".type_tit");
    let chinese_type: string;
    if (typeTitElement?.textContent) {
        chinese_type = typeTitElement.textContent?.replace(/（.*）/g, "").replace(/.*\./g, "").trim();
        // @ts-ignore
        return [ch2number_map[chinese_type], ch2en_map[chinese_type]];
    } else {
        // Handle the case where the element is not found
        console.error("Type title element not found");
        return [null, null];
    }
}

const letterToNumber = (letter: string|null|undefined): number => {
    if (!letter) throw new InfoNotFoundError("没有找到答案选项");
    // 将字母转换为大写，确保统一处理
    const upperLetter = letter.toUpperCase();

    // 检查输入是否为单个字母
    if (upperLetter.length !== 1 || !/[A-Z]/.test(upperLetter)) {
        throw new InfoNotFoundError("没有找到答案选项");
    }

    // 获取字母的 Unicode 编码，并减去 'A' 的编码
    return upperLetter.charCodeAt(0) - 'A'.charCodeAt(0);
}

const run = async (): Promise<{success: boolean, message?: string}> => {
    let token = GM_getValue("token");
    if (token == undefined){
        token = prompt("请输入token");
        if(token == null) return {success: false, message: "未提供Token"};
        GM_setValue("token", token);
    }
    $("div.mark_item").each(
        (index: number, element: HTMLElement) => {
        const [question_type_number, question_type] = question_type_getter(index, element);
            if(question_type_number !== null && question_type !== null){
                try {
                    if (question_type_number === 0 || question_type_number === 1) {
                        simple_answer_getter(index, element, question_type);
                    } else if (question_type_number === 3) {
                        judgement_answer_getter(index, element, question_type);
                    } else if (question_type_number === 4 || question_type_number === 14) {
                        completion_answer_getter(index, element, question_type);
                    }
                } catch (e) {
                    const error = e as Error;
                    warnings.push(error.message);
                }
            }
        }
    )
    let body = {
        "questions": questions,
        "total": questions.length,
    }
    fetch(base_url + "/submit_answer", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + token,
        },
        body: JSON.stringify(body),
    }).then((res) => {
        if(res.status === 401||res.status === 403){
            GM_deleteValue("token");
            warnings.push("Token无效")
        }
        return res.json();
    })
        .then((res) => {
        if(res.success){
            console.log("提交成功");
            const newDiv = document.createElement("div")
            newDiv.className = "topicNumber_checkbox colorDeep fs14";
            newDiv.innerHTML = "提交成功"
            const topicNumberScrollElement = document.getElementById("topicNumberScroll")
            if (topicNumberScrollElement !== null) {
                topicNumberScrollElement.insertBefore(newDiv, topicNumberScrollElement.children[0]);
            }
        } else {
            throw new InfoNotFoundError("提交失败: "+res.errMessage);
        }
    })
        .catch((error) => {
        throw new InfoNotFoundError("提交失败: "+error)
    });
    return {success: true}
}

if(document.location.pathname === '/mooc-ans/mooc2/work/view'){
    run().then(() => {
        if(warnings.length != 0) {
            console.error(warnings.join("\n"));
            if(warnings.length > 5) alert(warnings.slice(0, 6).join("\n")+"\n and more");
            else alert(warnings.join("\n"));
        }
    });
}
